<?php
/*
Primary Author: Derek Shue
Secondary: Alex Arey, Sean Margison (Onyen vs. Non-onyen)
Updated: 12/10/2011
Module Description: The login controller displays forms for ONYEN and non-ONYEN
login pages and uses Zend_Auth_Adaptors to validate login.
*/

class LoginController extends Zend_Controller_Action
{

    public function init()
    {
        /*No initialization needed. */
    }
    /**
    * If the controller is accessed with no action, assume onyen login.
    */
    public function indexAction(){
	return $this->_helper->redirector('onyenlogin');
    }
    /**
    * Partnerlogin action uses LOGINNAME and PW from partner login form and
    * Uses a Zend_Auth_Adaptor_Interface to check credentials in the database.
    */
    public function partnerloginAction()
    {
	
        $form = new Application_Form_PartnerLogin();
        $form->submit->setLabel('Login');
        $this->view->form = $form;
		
	if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {		
		$loginname = $form->getValue('LOGINNAME');
                $pw = $form->getValue('PW');
		$auth = Zend_Auth::getInstance();
		$authAdapter = new cpAuthAdapter($loginname,$pw);
		$result = $auth->authenticate($authAdapter);
		if($result->isValid())
		{
            return $this->_helper->redirector('index', 'index');
        }
		else{
		    echo "Login Unsuccessful";
			$form->submit->setLabel('Try Login Again');
	        }													 
          }
        }
    }
    
    /**
    * Onyen login action uses the Zend LDAP auth adaptor for authentication.
    */
    public function onyenloginAction()
    {
	
        $form = new Application_Form_OnyenLogin();
        $form->submit->setLabel('Login');
        $this->view->form = $form;
		
	if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {		
			$loginname = $form->getValue('LOGINNAME');
                $pw = $form->getValue('PW');
				
				
		$auth = Zend_Auth::getInstance();
		$authAdapter = new onyenAuthAdapter($loginname,$pw);
		$result = $auth->authenticate($authAdapter);
		
		if($result->isValid())
		{
               return $this->_helper->redirector('index', 'index');
        }else{
		echo "Login Unsuccessful";
		    $form->submit->setLabel('Try Login Again');

		}													 
            }
        }
    }
    
    /**
    * Logout clears Zend_Auth identity to end user session.
    */
    public function logoutAction(){
	Zend_Auth::getInstance()->clearIdentity();
	$ns = new Zend_Session_Namespace('Default');
	//clear 'internapp' from default namespace. This was set if student started filling
	//out an intern request without submitting, and should be cleared on logout.
	if (isset($ns->internapp))
		unset($ns->internapp);
	$this->_helper->redirector('index', 'index');
    }
}

/**
* Class onyenAuthAdapter uses zend LDAP authentication to access the UNC ONYEN servers.
*/
class onyenAuthAdapter implements Zend_Auth_Adapter_Interface
{
	protected $_username;
    protected $_password;
    /**
     * Sets username and password for authentication
     */
    public function __construct($username, $password)
    {
        $this->_username = $username;
        $this->_password = $password;
    }

	public function authenticate()
    {
		$auth = Zend_Auth::getInstance();
		$config = new Zend_Config_Ini('../application/configs/application.ini','production');//get config for LDAP
		$log_path = $config->ldap->log_path;//bookkeeping details
		$options = $config->ldap->toArray();//get options from config
		unset($options['log_path']);//bookkeeping
		
		$authAdapter = new Zend_Auth_Adapter_Ldap($options,$this->_username,$this->_password);
		$resultLdap = $auth->authenticate($authAdapter);	
		if($resultLdap->isValid()){	
			$users = new Application_Model_DbTable_Users();
			
			//successful authentication
			//code var indicates status for debugging
			$code = 1;
			
			try{
				//does user exist in user table
				//throws exception if user does not exist
				$session_info = $users->getUser("LOGINNAME = '". (string)$this->_username . "'");
			}
			catch(Exception $e){
				//add user if not present, with null password indicating onyen login
				$users->addUser($this->_username, "", 0, "student");
				$session_info = $users->getUser("LOGINNAME = '". (string)$this->_username . "'");
			}	
				//obtain session information
				$uname = $session_info['LOGINNAME'];
				$uid = $session_info['ID'];
				$urank = $session_info['RANK'];
				$utype = $session_info['TYPE'];
				//create session identity
				$userId = new Application_Model_UserIdentity($uname,$uid,$urank,$utype);
		}
		else
		{
			$code = -3;
			$userId = new Application_Model_UserIdentity('0',0,0,'0');
		}	
		//set session identity
		$res = new Zend_Auth_Result($code, $userId);
		return $res;
	}
}

/**
* Class cpAuthAdapter verifies community parter and other non-onyen logins by consulting the users
* table in the database.
*/
class cpAuthAdapter implements Zend_Auth_Adapter_Interface
{
    protected $_username;
    protected $_password;
    /**
     * Sets username and password for authentication
     */
    public function __construct($username, $password)
    {
        $this->_username = $username;
        $this->_password = $password;
    }
     
    /**
    * Performs an authentication attempt
    * @throws Zend_Auth_Adapter_Exception
    * @return Zend_Auth_Result
    */
    public function authenticate()
    {
	$usersTable = new Application_Model_DbTable_Users();
	try{
		
	    $session_info = $usersTable->getUser("LOGINNAME = '". (string)$this->_username . "'" . 
		    " AND " . "PW = '" . md5($this->_password) . "'" );
        
		$code = 1;
	    $uname = $session_info['LOGINNAME'];
	    $uid = $session_info['ID'];
	    $urank = $session_info['RANK'];
        $utype = $session_info['TYPE'];
	    $userId = new Application_Model_UserIdentity($uname,$uid,$urank,$utype);
	
	}catch(Exception $e){
	    $code = -3;
	    $userId = new Application_Model_UserIdentity('0',0,0,'0');
	}
	
	$res =  new Zend_Auth_Result($code,$userId);
	return $res;
	
	}
}


